package com.zHan.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zHan.sky.common.contant.MessageConstant;
import com.zHan.sky.common.exception.DeletionNotAllowedException;
import com.zHan.sky.entity.Category;
import com.zHan.sky.entity.Dish;
import com.zHan.sky.entity.Setmeal;
import com.zHan.sky.mapper.CategoryMapper;
import com.zHan.sky.service.CategoryService;
import com.zHan.sky.service.DishService;
import com.zHan.sky.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;

    @Autowired
    private SetmealService setmealService;

    /**
     * 根据id删除分类
     * @param id
     * @return
     */
    @Override
    public void removeById(Long id) {
        //判断当前分类是否关联菜品
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);
        int dishCount = dishService.count(dishLambdaQueryWrapper);

        //已关联菜品
        if (dishCount > 0) {
            //抛出业务异常
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_DISH);
        }

        //判断当前分类是否关联套餐
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId, id);
        int setmealCount = setmealService.count(setmealLambdaQueryWrapper);

        //已关联套餐
        if (setmealCount > 0) {
            // 抛出业务异常
            throw new DeletionNotAllowedException(MessageConstant.CATEGORY_BE_RELATED_BY_SETMEAL);
        }

        //都未关联，正常删除
        super.removeById(id);
    }
}
